import whiteList from "./pre-defined/white-list";
import {Next} from "koa";
import { v4 as uuid } from "uuid";
import {
  randomNumber,
  performanceMonitor,
} from "mmb";
import { AppCTX } from "../types/koaExtend"
const blockLogRequestBody = ["/mkt/orderingPromotion/lock/", "/_esp/method/"];
const blockLogResponseBody = ["/mkt/orderingPromotion/lock/", "/_esp/method/"];


export default async (ctx: AppCTX, next: Next) => {
  const reqUrl = ctx.request.url;
  const needRequestBody =
    blockLogRequestBody.findIndex((item) => reqUrl.startsWith(item)) === -1;
  const needResponseBody =
    blockLogResponseBody.findIndex((item) => reqUrl.startsWith(item)) === -1;
  const _tsBegin = Date.now();
  let trackingId
  if (whiteList.logger.findIndex((item) => reqUrl.startsWith(item)) === -1) {
    trackingId = uuid() + "$" + randomNumber(6);
    ctx.state.trackingId = trackingId
    const enterInfo = `---enter---${trackingId}::${reqUrl}`;
    console.log(enterInfo);
    if (needRequestBody && ['POST', "PUT"].includes(ctx.request.method)) {
      console.log(`request body=>`, JSON.stringify(ctx.body))
    }
  }
  await next();
  if (whiteList.logger.findIndex((item) => reqUrl.startsWith(item)) === -1) {
    if (needResponseBody) {
      console.log(`response body=>`, JSON.stringify(ctx.body))
    } else {
      console.log('skip response body')
    }
    const exitInfo = `---exit---${trackingId}::${reqUrl} 耗时:${(Date.now() - _tsBegin)}`;
    console.log(exitInfo);
  }
  performanceMonitor(`完整请求 ${reqUrl}`, _tsBegin);
};
